package com.jcfy.framework.base;

import com.jcfy.common.constant.Constants;
import com.jcfy.framework.web.controller.BaseController;
import com.jcfy.project.module.domain.TUser;
import com.jcfy.project.module.service.ITUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

/**
 * @author hushuai
 * @version 1.0
 * @name ClientBaseController
 * @desc TODO controller基类
 * @date 2020/5/13 15:42:45
 */
public class ClientBaseController extends BaseController {

    protected final Logger logger = LoggerFactory.getLogger(ClientBaseController.class);

    @Resource
    ITUserService tUserService;

    /**
     * 从session中移除用户信息
     *
     */
    protected void removeSessionUser() {
        TUser user = getSessionUser();

        TUser _user = new TUser();
        _user.setUserId(user.getUserId());
        _user.setToken(RandomStringUtils.randomAlphanumeric(45));
        _user.setTokenDate(new Date());
        tUserService.updateTUser(_user);
    }

    /**
     * 设置session中用户信息
     *
     * @param user
     * @return 登陆token
     */
    protected String setSessionUser(TUser user) {
        if (user != null && !StringUtils.isBlank(user.getToken()) && user.getTokenDate().after(new Date())) {
            return user.getToken();
        }
        if (user != null && (StringUtils.isBlank(user.getToken()) || user.getTokenDate().before(new Date()))) {
            String token = RandomStringUtils.randomAlphanumeric(45);
            user.setToken(token);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, Constants.CLIENT_TOKEN_OVERDUE);
            user.setTokenDate(calendar.getTime());
            int num = tUserService.updateTUser(user);
            if (num > 0) {
                return token;
            }
        }
        return null;
    }


    /**
     * 获取session中的登陆用户对象
     *
     * @return
     */
    protected TUser getSessionUser() {
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return tUserService.getByToken(token);
    }


    /**
     * 获取session中的登陆用户id
     *
     * @return
     */
    protected Long getSessionUserId() {
        TUser user = getSessionUser();
        if (user == null) {
            return null;
        }
        return user.getUserId();
    }
}
